package com.yunze.task.yunze.Automation;

import com.alibaba.fastjson.JSON;
import com.yunze.apiCommon.mapper.mysql.YzCardRouteMapper;
import com.yunze.common.core.domain.entity.SysDictData;
import com.yunze.common.mapper.mysql.YzCardMapper;
import com.yunze.common.mapper.mysql.YzExecutionTaskMapper;
import com.yunze.common.mapper.mysql.automationCC.YzAutomationCcHisMapper;
import com.yunze.common.mapper.mysql.automationCC.YzAutomationCcMapper;
import com.yunze.common.mapper.mysql.automationCC.YzAutomationCcMonthlyRecorMapper;
import com.yunze.common.mapper.mysql.automationCC.YzAutomationCcUrlMapper;
import com.yunze.common.utils.Email.EmailCc;
import com.yunze.common.utils.yunze.VeDate;
import com.yunze.common.utils.yunze.WriteCSV;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * NB 超用量 300 MB 邮件通知
 */

@Slf4j
@Component
public class EmailNBExceedMQ {

    @Resource
    private YzAutomationCcHisMapper yzAutomationCcHisMapper;
    @Resource
    private EmailCc emailCc;
    @Resource
    private YzCardMapper yzCardMapper;
    @Resource
    private YzAutomationCcMapper yzAutomationCcMapper;
    @Resource
    private YzAutomationCcUrlMapper yzAutomationCcUrlMapper;
    @Resource
    private YzAutomationCcMonthlyRecorMapper yzAutomationCcMonthlyRecorMapper;
    @Resource
    private YzExecutionTaskMapper yzExecutionTaskMapper;
    @Resource
    private WriteCSV writeCSV;
    @Resource
    private YzCardRouteMapper yzCardRouteMapper;

    @RabbitHandler
    @RabbitListener(queues = "admin_clearEecordNBExceed_queue")
    public void clearEecordNBExceed() {

        int dCount = yzAutomationCcMonthlyRecorMapper.del(null);
        System.out.println("清空 yzAutomationCcMonthlyRecorMapper.del = "+dCount);
    }





    /**
     * 邮件抄送
     */
    @RabbitHandler
    @RabbitListener(queues = "admin_NBExceed_queue")
    public void NBExceed(String msg) {
        if (StringUtils.isEmpty(msg)) {
            return;
        }

        Map<String,Object> Pmap = JSON.parseObject(msg);
        Map<String, Object> findMap = new HashMap<>();
        findMap.put("trigger_type", "15"); //自动化触发类型 NB卡超300MB


        Map<String, Object> fdMap = new HashMap<>();
        //获取 用户信息
        List<Map<String, Object>> userArr = yzCardMapper.findUser_simple(fdMap);
        fdMap.put("dictType","yunze_card_status_ShowId");
        List<Map<String, Object>> stateOptions = yzCardMapper.selectDictDataByType(fdMap);//卡状态
        fdMap.put("dictType","yunze_card_card_type");
        List<Map<String, Object>> card_types = yzCardMapper.selectDictDataByType(fdMap);//卡状态
        fdMap.put("dictType","yunze_customize_whether");
        List<Map<String, Object>> customize_whether = yzCardMapper.selectDictDataByType(fdMap);//卡状态
        fdMap.put("dictType","yz_cardConnection_type");
        List<Map<String, Object>> cardConnection_type =  yzCardMapper.selectDictDataByType(fdMap);//卡状态
        fdMap.put("dictType","yunze_card_network_type");
        List<Map<String, Object>> card_network_type = yzCardMapper.selectDictDataByType(fdMap);//卡状态






        //获取通道信息
        Map<String,Object> find_simpleMap = new HashMap<String,Object>();
        find_simpleMap.put("cd_operator_type",null);//
        find_simpleMap.put("channel_id",null);//
        List<Map<String,Object>> routeArr = yzCardRouteMapper.find_simple(find_simpleMap);



       // System.out.println(Count);


            List<Map<String, Object>> AutomationCcArr = yzAutomationCcMapper.findConcise(findMap);//获取自动化 抄送 组
            if (AutomationCcArr != null && AutomationCcArr.size() > 0) {

                Map<String, Object> findNBExceed_Map = new HashMap<>();
                findNBExceed_Map.put("network_type","1");//NB
                findNBExceed_Map.put("dimensionField","1");// used 用量
                findNBExceed_Map.put("dimensionType","1");// >=
                findNBExceed_Map.put("dimensionValue","300.00");// 300MB

                Map<String, Object> findCCIccid_Map = new HashMap<>();
                findCCIccid_Map.put("trigger_type","15");//自动化触发类型 NB卡超300MB
                List<String> ccIccidArr = yzAutomationCcMonthlyRecorMapper.findCCIccid(findCCIccid_Map);//获取 指定 类型

                if(ccIccidArr!=null && ccIccidArr.size()>0){//已经抄送过的 卡号 进行 过滤
                    findNBExceed_Map.put("notInIccidArr",ccIccidArr);// 300MB
                }



                for (int i = 0; i < AutomationCcArr.size(); i++) {





                    Map<String, Object> CCObj = AutomationCcArr.get(i);
                    List<Map<String, Object>> AutomationCcUrlArr = yzAutomationCcUrlMapper.findConcise(CCObj);//获取自动化 抄送 邮箱

                    Object obj_cid = CCObj.get("channel_id");
                    if(obj_cid!=null && obj_cid.toString().length()>0){
                         List<String> channel_id = new ArrayList<>();

                       String str_cid =  obj_cid.toString();
                        if(str_cid.indexOf(",")!=-1){
                            String[] sarr = str_cid.split(",");
                            for (int j = 0; j < sarr.length; j++) {
                                channel_id.add(sarr[j]);
                            }
                        }else {
                            channel_id.add(str_cid);
                        }
                        findNBExceed_Map.put("channel_id",channel_id);// 指定 通道
                    }

                    List<Map<String, Object>> outCardArr = yzCardMapper.outCard(findNBExceed_Map);//获取 NB 用量 >= 300MB 卡号


                if(outCardArr != null && outCardArr.size() > 0 ){
                    String taskId = "";
                    String create_by = " [平台] - " + " [自动化] ";
                    String newName = UUID.randomUUID().toString().replace("-", "") + "_NBExceed";
                    String task_name = " NB超套300MB预警-id-[" + CCObj.get("id").toString() + "]-[" + VeDate.getStringDate() + "]";
                    String SaveUrl = "/getcsv/" + newName + ".csv";
                    Map<String, Object> task_map = new HashMap<String, Object>();
                    task_map.put("auth", create_by);
                    task_map.put("task_name", task_name);
                    task_map.put("url", SaveUrl);
                    task_map.put("agent_id", "100");
                    task_map.put("type", "41"); //对应 字典表的 执行日志类别  NB超套300MB预警
                    yzExecutionTaskMapper.add(task_map);//添加执行 任务表

                    Map<String, Object> addMap = new HashMap<>();
                    addMap.put("trigger_type","15");

                    List<String> iccid_arrs = new ArrayList<>();

                    List<Map<String,Object>> out_list = new ArrayList<Map<String,Object>>();
                    //循环添加单卡数据信息
                    for (int j = 0; j < outCardArr.size(); j++) {
                        Map<String,Object> CarMap =  outCardArr.get(j);

                        iccid_arrs.add(CarMap.get("iccid").toString());
                        //写入 卡状态 status_value
                        CarMap  =  WriteDic(CarMap,stateOptions,"status_id","status_value");
                        //写入 卡类型 type_value
                        CarMap  =  WriteDic(CarMap,card_types,"type","type_value");
                        //写入 gprs是否开启 gprs_value
                        CarMap  =  WriteDic(CarMap,customize_whether,"gprs","gprs_value");
                        //写入 未订购资费 是否 轮询停机 gprs_value
                        CarMap  =  WriteDic(CarMap,customize_whether,"is_Disconnected","Disconnected_value");
                        //写入 断开网状态 connection_status
                        CarMap  =  WriteDic(CarMap,cardConnection_type,"connection_status","connection_value");
                        //写入 卡板网络类型 card_network_type
                        CarMap  =  WriteDic(CarMap,card_network_type,"network_type","network_type_value");




                        //写入 API 通道信息
                        CarMap  =  WriteCarRout(CarMap,routeArr);
                        //写入 所属用户信息
                        CarMap  =  WriteCarUser(CarMap,userArr);

                        //删除导出不需要的字段
                        CarMap.remove("status_id");
                        CarMap.remove("type");
                        CarMap.remove("package_id");
                        CarMap.remove("agent_id");
                        CarMap.remove("channel_id");
                        CarMap.remove("gprs");
                        CarMap.remove("is_Disconnected");
                        CarMap.remove("connection_status");

                        out_list.add(CarMap);
                    }

                    String Outcolumns[] = {};
                    String keys[] = {};
                        Outcolumns = new String[]{"虚拟编号", "MSISDN", "ICCID", "IMSI", "IMEI", "出库日期", "发货日期",        "激活日期",        "到期日期",     "周期用量", "系统剩余用量", "用量同步时间", "分组",            "未订购资费是否停机",     "所属企业", "备注",     "卡状态",      "卡状态同步时间", "断开网状态",        "卡类型",    "网络类型",           "GPRS是否开启", "API通道", "运营商类型", "所属用户"};
                              keys = new String[]{"vid",     "msisdn",  "iccid","imsi", "imei","out_of_stock","deliver_date","activate_date","due_expire_time","used",    "remaining",   "flowTime","customize_grouping","Disconnected_value"  ,"dept_name","remarks","status_value","stateTime",     "connection_value","type_value","network_type_value","gprs_value","cd_name","dict_label","user_name"};

                    int Count = outCardArr.size();

                    writeCSV.Write(newName,out_list,Outcolumns,null,keys);
                    Map<String, Object> emailMap = new HashMap<>();
                    taskId = ""+task_map.get("id");
                    emailMap.put("taskId",taskId);// 获取 执行任务表的ID
                    emailMap.put("describe","NB超套300MB预警-"+Count+" 张");
                    emailMap.put("heartext","NB超套300MB预警-"+Count+" 张");
                    yzExecutionTaskMapper.set_end_time(task_map);

                    addMap.put("iccid_arrs",iccid_arrs);
                    yzAutomationCcMonthlyRecorMapper.save(addMap);//新增抄送记录




                        if ( AutomationCcUrlArr != null && AutomationCcUrlArr.size() > 0) {
                            String execution_template = CCObj.get("execution_template").toString();

                            emailMap.put("Count", Count);
                            if (execution_template.equals("1")) {
                                for (int j = 0; j < AutomationCcUrlArr.size(); j++) {
                                    Object eM = AutomationCcUrlArr.get(j).get("email");
                                    if (eM != null && eM.toString().length() > 0) {
                                        String SendEmail = eM.toString();
                                        Map<String, Object> saveHisMap = new HashMap<>();
                                        saveHisMap.put("cc_id", CCObj.get("id"));
                                        saveHisMap.put("cc_url", "");
                                        saveHisMap.put("cc_email", SendEmail);
                                        saveHisMap.put("cc_state", "1");//已抄送


                                        Map<String, Object> CCMap = new HashMap<>();



                                        CCMap.put("Count",Count);
                                        CCMap.put("emailMap",emailMap);
                                        String cc_parameter = JSON.toJSONString(CCMap);
                                        cc_parameter = cc_parameter.length() > 500 ? cc_parameter.substring(0, 500) : cc_parameter;
                                        saveHisMap.put("cc_parameter", cc_parameter);
                                        Map<String, Object> Rmap = null;
                                        Boolean bool = false;
                                        String remark = "", cc_result = "0";
                                        try {
                                            Rmap =  emailCc.PerformTasks_default(emailMap, SendEmail, "系统预警");
                                            bool = (Boolean) Rmap.get("bool");
                                            if (bool) {
                                                cc_result = "1";
                                            }
                                        } catch (Exception e) {
                                            remark = e.getMessage();
                                            remark = remark.length() > 240 ? remark.substring(0, 240) : remark;
                                        }
                                        saveHisMap.put("remark", remark);
                                        saveHisMap.put("cc_result", cc_result);
                                        boolean saveHis = yzAutomationCcHisMapper.save(saveHisMap) > 0;
                                        log.info(">>自动化 [NBExceed] 已抄送邮箱{}  - 插入抄送记录 bool   {} <<", SendEmail, saveHis);
                                    } else {
                                        log.error(">>自动化 [NBExceed] 抄送邮箱未获取到  - 抄送取消  {} <<", eM);
                                    }
                                }
                            } else {
                                log.error(">>自动化 [NBExceed] 抄送模板不批对  - 抄送取消  {} <<");
                            }
                        } else {
                            log.error(">>自动化 [NBExceed] 获取自动化 抄送 邮箱 未找到数据 - 抄送取消  {} <<");
                        }
                    }


                }
            }
        }


    /**
     * 写入 所属用户信息
     * @param CarMap
     * @param userArr
     * @return
     */
    protected Map<String,Object> WriteCarUser (Map<String,Object> CarMap,List<Map<String,Object>> userArr){

        Map<String,Object> Rmap = new HashMap<String,Object>();
        String user_id = CarMap.get("user_id")!=null?CarMap.get("user_id").toString():null;
        boolean bool = false;
        if(userArr!=null && user_id !=null){
            for (int i = 0; i < userArr.size(); i++) {
                Map<String,Object> UserMap =  userArr.get(i);
                String Fuser_id = UserMap.get("user_id").toString();
                if(Fuser_id.equals(user_id)){
                    CarMap.put("user_name",UserMap.get("user_name"));
                    bool = true;
                    break;
                }
            }
        }
        if(!bool){
            CarMap.put("user_name","");
        }
        return CarMap;
    }



    /**
     * 写入 API 通道信息
     * @param CarMap
     * @param routeArr
     * @return
     */
    protected Map<String,Object> WriteCarRout (Map<String,Object> CarMap,List<Map<String,Object>> routeArr){
        String channel_id = CarMap.get("channel_id")!=null?CarMap.get("channel_id").toString():null;
        boolean bool = false;
        if(routeArr!=null && channel_id!=null){
            for (int i = 0; i < routeArr.size(); i++) {
                Map<String,Object> RoutMap =  routeArr.get(i);
                String cd_id = RoutMap.get("cd_id").toString();
                if(cd_id.equals(channel_id)){
                    CarMap.put("cd_name",RoutMap.get("cd_alias"));
                    CarMap.put("dict_label",RoutMap.get("dict_label"));
                    bool = true;
                    break;
                }
            }
        }
        if(!bool){
            CarMap.put("cd_name","");
            CarMap.put("dict_label","");
        }
        return CarMap;
    }






    /**
     * 字典获取
     * @param CarMap 写入Map
     * @param DictDataArr 字典 list
     * @param basis 获取依据 字段 与 dictValue 判断
     * @param fieldName 返回字段名称
     * @return
     */
    public Map<String,Object> WriteDic (Map<String,Object> CarMap,List<Map<String, Object>> DictDataArr,String basis,String fieldName){

        Map<String,Object> Rmap = new HashMap<String,Object>();
        String status_id = CarMap.get(basis)!=null?CarMap.get(basis).toString():null;
        boolean bool = false;
        if(status_id!=null){
            for (int i = 0; i < DictDataArr.size(); i++) {
                Map<String, Object>  dictData =  DictDataArr.get(i);
                String dictValue = dictData.get("dict_value").toString();
                if(dictValue.equals(status_id)){
                    CarMap.put(fieldName,dictData.get("dict_label"));
                    bool = true;
                    break;
                }
            }
        }
        //字段 默认值
        if(!bool){
            CarMap.put(fieldName,"");
        }
        return CarMap;
    }





    /**
     * 邮件抄送 重试
     *
     * cc_count 重试次数
     */
    @RabbitHandler
    @RabbitListener(queues = "admin_PassagewayCount_queue")
    public void RetryCC(String msg) {
        if (StringUtils.isEmpty(msg)) {
            return;
        }
        Map<String,Object> Pmap = JSON.parseObject(msg);
        Integer cc_count = Integer.parseInt(Pmap.get("cc_count").toString());

        Map<String, Object> findNotPerformed_Map = new HashMap<>();
        findNotPerformed_Map.put("trigger_type", "6");
        findNotPerformed_Map.put("cc_count", cc_count);//重试次数
        List<Map<String, Object>> CcArr = yzAutomationCcHisMapper.findNotPerformed(findNotPerformed_Map);
        if (CcArr != null && CcArr.size() > 0) {
            //2.获取
            for (int i = 0; i < CcArr.size(); i++) {
                Map<String, Object> Cc_Map = CcArr.get(i);
                Map<String, Object> MsgMap = JSON.parseObject(Cc_Map.get("cc_parameter").toString());

                String SendEmail = Cc_Map.get("cc_email").toString();
                Map<String, Object> updHisMap = new HashMap<>();
                updHisMap.put("id", Cc_Map.get("id"));
                Map<String, Object> Rmap = null;
                Boolean bool = false;
                String remark = "", cc_result = "0";
                try {
                    Rmap = emailCc.UndividedChannel_default(MsgMap, SendEmail);
                    bool = (Boolean) Rmap.get("bool");
                    if (bool) {
                        cc_result = "1";
                    }
                } catch (Exception e) {
                    remark = e.getMessage();
                    remark = remark.length() > 240 ? remark.substring(0, 240) : remark;
                }
                updHisMap.put("remark", remark);
                updHisMap.put("cc_result", cc_result);
                boolean updHis = yzAutomationCcHisMapper.updCcCount(updHisMap) > 0;
                System.out.println(">>自动化  [EmailPassageway]  已抄送邮箱" + SendEmail + "  - 抄送 bool   {" + bool + "}  修改 bool {" + updHis + "}<<");
            }
        }
    }





    /**
     * 写入 套餐详细信息
     * @param CarMap
     * @param CardFlowArr
     * @return
     */
    protected Map<String,Object> WriteCarFlow (Map<String,Object> CarMap,List<Map<String,Object>> CardFlowArr){

        Map<String,Object> Rmap = new HashMap<String,Object>();
        String iccid = CarMap.get("iccid")!=null?CarMap.get("iccid").toString():null;
        boolean bool = false;
        if(CardFlowArr!=null && iccid!=null){
            for (int i = 0; i < CardFlowArr.size(); i++) {
                Map<String,Object> FlowMap =  CardFlowArr.get(i);
                String Ficcid = FlowMap.get("iccid").toString();
                if(Ficcid.equals(iccid)){
                    CarMap.put("true_flow",FlowMap.get("true_flow"));
                    CarMap.put("use_so_flow_sum",FlowMap.get("use_so_flow_sum"));
                    CarMap.put("Percentage",FlowMap.get("Percentage"));
                    CarMap.put("surplus",FlowMap.get("surplus"));
                    CarMap.put("packet_name",FlowMap.get("packet_name"));
                    CarMap.put("packet_valid_time",FlowMap.get("packet_valid_time"));
                    CarMap.put("packet_valid_name",FlowMap.get("packet_valid_name"));
                    CardFlowArr.remove(FlowMap);
                    bool = true;
                    break;
                }
            }
        }
        //字段 默认值
        if(!bool) {
            CarMap.put("true_flow","");
            CarMap.put("use_so_flow_sum","");
            CarMap.put("Percentage","");
            CarMap.put("surplus","");
            CarMap.put("packet_name","");
            CarMap.put("packet_valid_time","");
            CarMap.put("packet_valid_name","");
        }

        Rmap.put("CarMap",CarMap);
        Rmap.put("CardFlowArr",CardFlowArr);
        return Rmap;
    }

}
